package com.bsoft.exchange.service;

import com.bsoft.exchange.dao.his.*;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.param.FeeSettlement;
import com.bsoft.exchange.param.SignParam;
import com.bsoft.exchange.pojo.BookingRegisterPojo;
import com.bsoft.exchange.pojo.OutResponse;
import com.bsoft.exchange.pojo.ReturnVisitPaymentAndSettlementPojo;
import com.bsoft.exchange.pojo.SyncOrderStatePoJo;
import com.bsoft.exchange.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.sql.SQLException;
import java.util.*;

@Service
public class AppointmentService {

    public static final String FormatStr = "yyyy-MM-dd";

    private static final Logger logger = LoggerFactory.getLogger(AppointmentService.class);

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    DoctorMapper doctorMapper;

    @Autowired
    AppointmentMapper appointmentMapper;

    @Autowired
    SourceNumberMapper sourceNumberMapper;

    @Autowired
    DepartmentScheduleMapper departmentScheduleMapper;

    @Autowired
    DoctorScheduleMapper doctorScheduleMapper;

    @Autowired
    IdentityManager identityManager;

    @Autowired
    CreateOrderNoMapper createOrderNoMapper;

    @Autowired
    PatientMapper patientMapper;

//    private int yyxh;
//    private String sfzh;

    @Autowired
    AppointmentInfomationMapper appointmentInfomationMapper;

    @Autowired
    AppointmentRegisterMapper appointmentRegisterMapper;

    @Autowired
    SystemConfigMapper systemConfigMapper;

    @Autowired
    RegisterMapper registerMapper;

    @Autowired
    PaymentInformationMapper paymentInformationMapper;

    @Autowired
    UserBillManager userBillManager;

    @Autowired
    QueueCallService queueCallService;

    @Autowired
    YBService ybService;

    public BaseResponse<String> appointmentPay(
            String hospitalCode,
            String hisOrderNumber,
            String outOrderNumber,
            String payMode,
            String agtOrderNumber,
            Double payAmount,
            String payTime,
            String notify,
            String channelOrderNumber,
            Integer outpatientType,
            Integer enterQueue) {

        BaseResponse<String> baseResponse = new BaseResponse<>();

        baseResponse = appointmentPayOrder(hospitalCode,
                hisOrderNumber,
                outOrderNumber,
                payMode,
                agtOrderNumber,
                payAmount,
                payTime,
                notify,
                channelOrderNumber,
                outpatientType);

        if (baseResponse.getCode() != Constant.successTag && baseResponse.getCode() != Constant.successResponse) {
            return baseResponse;
        }

        baseResponse = appointmentPayHis(hospitalCode,
                hisOrderNumber,
                outOrderNumber,
                payMode,
                agtOrderNumber,
                payAmount,
                payTime,
                notify,
                channelOrderNumber,
                outpatientType,
                enterQueue);

        if (baseResponse.getCode() != Constant.successTag && baseResponse.getCode() != Constant.successResponse) {
            return baseResponse;
        }

        //队列改成和HIS支付同一事务
//		baseResponse = appointmentPayPdjh( hospitalCode,
//				 hisOrderNumber,
//				 outOrderNumber,
//				 payMode,
//				 agtOrderNumber,
//				 payAmount,
//				 payTime,
//				 notify,
//				 channelOrderNumber,
//				 outpatientType,baseResponse.getData());
//
//		if(baseResponse.getCode() !=Constant.successTag && baseResponse.getCode() !=Constant.successResponse){
//	        return baseResponse;
//		}
//
        return baseResponse;
    }

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> appointmentPayPdjh(String hospitalCode,
                                                   String hisOrderNumber,
                                                   String outOrderNumber,
                                                   String payMode,
                                                   String agtOrderNumber,
                                                   Double payAmount,
                                                   String payTime,
                                                   String notify,
                                                   String channelOrderNumber,
                                                   Integer outpatientType, String ghmx) {
        BaseResponse<String> baseResponse = new BaseResponse<>();
        //进入排队叫号
        try {
            BaseResponse<String> pdjhResponse = queueCallService.createPdjh(Integer.parseInt(ghmx), Integer.parseInt(hospitalCode));
        } catch (SQLException e) {

            e.printStackTrace();

            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("进入排队叫号失败!");

            return baseResponse;
        }

        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(notify);
        return baseResponse;
    }


    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> appointmentPayOrder(
            String hospitalCode,
            String hisOrderNumber,
            String outOrderNumber,
            String payMode,
            String agtOrderNumber,
            Double payAmount,
            String payTime,
            String notify,
            String channelOrderNumber,
            Integer outpatientType) {

        BaseResponse<String> baseResponse = new BaseResponse<>();

        try {

            Long jgid;
            if (hospitalCode == null || "".equals(hospitalCode)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("医院代码不能为空!");
                return baseResponse;
            }
            jgid = Long.parseLong(hospitalCode);

            if (outOrderNumber == null || "".equals(outOrderNumber)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("商户订单号不能为空!");
                return baseResponse;
            }
//			Long shddh;
//			shddh = Long.parseLong(outOrderNumber);

			/*if (payMode == null || "".equals(payMode)) {
				baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("支付方式不能为空!");
				return baseResponse;
			}
			int zffs;
			zffs = Integer.parseInt(payMode);*/

            createOrderNoMapper.updateShddhYwzt(outOrderNumber, 1, jgid.intValue());
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("更新商户订单号支付状态失败");
        }

        baseResponse.setCode(Constant.successTag);

        return baseResponse;
    }

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> appointmentPayHis(
            String hospitalCode,
            String hisOrderNumber,
            String outOrderNumber,
            String payMode,
            String agtOrderNumber,
            Double payAmount,
            String payTime,
            String notify,
            String channelOrderNumber,
            Integer outpatientType,
            Integer enterQueue) {

        BaseResponse<String> baseResponse = new BaseResponse<>();

        String ret = "支付失败!";
        Long jgid;
        Long yyxh;
        jgid = 1L;
        yyxh = Long.parseLong(hisOrderNumber);
        Date zfsj;
        try {
            if (null != payTime && !"".equals(payTime)) {
                zfsj = DateUtil.stringToDate(payTime);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //根据预约序号获取预约信息
        AppointmentInfomationDomain appointmentInfomation = appointmentInfomationMapper.getAppointmentInfoById(yyxh);
        if (appointmentInfomation == null) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("根据预约序号" + hisOrderNumber + "获取预约信息失败!");

            return baseResponse;
        }

        if (appointmentInfomation.getYyzt() != null && appointmentInfomation.getYyzt() > 0) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("该预约序号" + hisOrderNumber + "已经挂号!");

            return baseResponse;
        }

        //根据预约序号 获取号源信息
        SourceNumberDomain sourceNumber = sourceNumberMapper.getSourceNumberByYyxh(yyxh);
        if (sourceNumber == null) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("根据预约序号" + hisOrderNumber + "获取号源信息失败!");

            return baseResponse;
        }

        if (outOrderNumber == null || "".equals(outOrderNumber)) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("商户订单号不能为空!");
            return baseResponse;
        }

        if (payMode == null || "".equals(payMode)) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("支付方式不能为空!");
            return baseResponse;
        }
        int zffs;
        zffs = Integer.parseInt(payMode);

//		Long shddh;
//		shddh = Long.parseLong(outOrderNumber);

        //根据号源信息，获取排班信息
        Integer ghrq;
        String ysdm;
        Map<String, Object> param = new HashMap<String, Object>();

        Map<String, Object> yspbParam = new HashMap<String, Object>();


        ghrq = DateUtil.getDayofweek(sourceNumber.getGzrq());
        param.put("jgid", jgid);
        param.put("ghrq", ghrq);
        param.put("zblb", sourceNumber.getZblb());
        param.put("ghks", sourceNumber.getGhks());

        ysdm = sourceNumber.getYsdm();
        Integer jzxh = 0;
        Integer ghlb;
        Integer czpb;
        boolean yspb = false;
        Integer ysbz = 0;
        Double ghje;
        Double zlje;
        Double zjfy;
        Double blje = 0.00;
        Double jzje = 0.00;
        Double qtys = 0.00;

        //获取节假日挂号费浮动参数
        String jjrfd = systemConfigMapper.getValueByConfigName(jgid, "MS_JJR_GHFFD");
        if (jjrfd == null || "".equals(jjrfd)) {
            jjrfd = "0";
        }
//		id_bldj = Double(gf_his_share_getpara(go_jgxx.il_jgid,"BLDJ","0.50","病历费单价"))
//		id_jzdj = Double(gf_his_share_getpara(go_jgxx.il_jgid,"JZDJ","0.50","就诊卡费单价"))

        //判断是否停挂
        //判断是否超过限

        //科室排班
        DepartmentScheduleDomain departmentSchedule = new DepartmentScheduleDomain();

        //医生排班
        DoctorScheduleDomain doctorSchedule = new DoctorScheduleDomain();

        //医生代码为空的为科室排班

        ysdm = sourceNumber.getYsdm();

        //排班 +1

        if (ysdm == null || "".equals(ysdm)) {

            departmentSchedule = departmentScheduleMapper.getDepartmentSchedule(param);

            if (departmentSchedule == null) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("查询对应的科室排班信息失败!");

                return baseResponse;
            }

            if (departmentSchedule.getTgbz() == 1) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("该科室已经停挂，请选择其他科室!");

                return baseResponse;
            }

            if (departmentSchedule.getYyxe() != 0 && departmentSchedule.getYyrs() >= departmentSchedule.getYyxe()) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("已超过科室预挂限额!");

                return baseResponse;
            }

            jzxh = departmentSchedule.getJzxh() + 1;
            ghlb = departmentSchedule.getGhlb();

            ghje = departmentSchedule.getGhf();
            if ("1".equals(jjrfd)) {
                ghje = departmentSchedule.getJjrghf();
            }
            zlje = departmentSchedule.getZlf();
            zjfy = (double) 0;
        } else {
            yspb = true;
            ysbz = 1;
            Date gzrq_begin = DateUtil.getDateByZeroTime(sourceNumber.getGzrq(), 0);
            Date gzrq_end = DateUtil.getDateByZeroTime(sourceNumber.getGzrq(), 1);

            yspbParam.put("jgid", 1);
            yspbParam.put("gzrq_begin", gzrq_begin);
            yspbParam.put("gzrq_end", gzrq_end);
            yspbParam.put("zblb", sourceNumber.getZblb());
            yspbParam.put("ksdm", sourceNumber.getGhks());
            yspbParam.put("ysdm", ysdm);

            doctorSchedule = doctorScheduleMapper.getDoctorSchedule(yspbParam);

            if (doctorSchedule == null) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("查询对应的医生排班信息失败!");

                return baseResponse;
            }
            if (doctorSchedule.getTgbz() == 1) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("该医生已经停挂，请选择其他科室或医生!");

                return baseResponse;
            }

            if (doctorSchedule.getYyxe() != 0 && doctorSchedule.getYyrs() >= doctorSchedule.getYyxe()) {
                baseResponse.setCode(Constant.breakTag);
                baseResponse.setMessage("已超过医生预挂限额!");

                return baseResponse;
            }
            jzxh = doctorSchedule.getJzxh() + 1;
            ghlb = doctorSchedule.getGhlb();
            ghje = doctorSchedule.getGhf();
            if ("1".equals(jjrfd)) {
                ghje = doctorSchedule.getJjrghf();
            }

            zlje = doctorSchedule.getZlf();
            zjfy = doctorSchedule.getZjfy();
        }

        String jzhm;
        jzhm = userBillManager.getJzhm(jgid, "");

        if (jzhm == null || "".equals(jzhm)) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("获取掌上医院默认员工就诊号码票据失败!");
            return baseResponse;
        }

        //排班 +1
        if (!yspb) {

            departmentScheduleMapper.updateDepartmentSchedule(param);

        } else {

            doctorScheduleMapper.updateDoctorSchedule(yspbParam);
        }

        //初诊判别
        czpb = registerMapper.checkFirstVisit(jgid, appointmentInfomation.getBrid());
        if (czpb == null || czpb <= 0) {
            czpb = 0;
        } else {
            czpb = 1;
        }
        //插入MS_GHMX  MS_YYGH  MS_GH_FKXX
        Long ghmx = identityManager.getMax("MS_GHMX", 1);
        Long jlxh = identityManager.getMax("MS_YYGH", 1);
        Long fkxh = identityManager.getMax("MS_GH_FKXX", 1);

        Date now = new Date();

        Long dzfpbz = 0L;
        //判断是否启用电子发票
        String value = systemConfigMapper.getValueByConfigName(jgid, "WECHAT_INVOICE_ACTIVATION");
        if(StringUtils.isNotBlank(value)){
            dzfpbz = Long.parseLong(value);
        }

        //MS_YYGH
//        AppointmentRegisterDomain appointmentRegister = new AppointmentRegisterDomain();
//
//        appointmentRegister.setYyxh(jlxh);
//        appointmentRegister.setJgid(jgid);
//        appointmentRegister.setYymm(" ");
//        appointmentRegister.setZcid((long) 0);
//        appointmentRegister.setDjgh(appointmentInfomation.getGhr());
//        appointmentRegister.setSbxh(ghmx);
//        appointmentRegister.setBrid(appointmentInfomation.getBrid());
//        appointmentRegister.setGhrq(now);
//        appointmentRegister.setGhbz(1);
//        appointmentRegister.setYylb(1);
//        appointmentRegister.setKsdm(sourceNumber.getGhks());
//        appointmentRegister.setYsdm(ysdm);
//        appointmentRegister.setZblb(sourceNumber.getZblb());
//        appointmentRegister.setYyrq(sourceNumber.getGzrq());
//        appointmentRegister.setJzxh(jzxh);
//        appointmentRegisterMapper.insertAppointmentRegister(appointmentRegister);
//        String fsfjylsh = "";
//        String ybkh = "";
        try {
            //MS_GHMX 新增applx,appzfdjh,appzfje
            RegisterDomain register = new RegisterDomain();
            register.setApplx(5L);
            register.setAppzffs("1");
            register.setAppzfdjh(agtOrderNumber);
            register.setAppzfje(payAmount);
            register.setSbxh(ghmx);
            register.setJgid(jgid);
            register.setJzxh(sourceNumber.getSxh());
            register.setGhcs(1);
            register.setGhje(ghje);
            register.setZlje(zlje);
            register.setZjfy(zjfy);
            register.setBlje(blje);
            register.setJzje(jzje);
            register.setQtys(qtys);
            register.setThbz(0);
            register.setCzpb(czpb);
            register.setMzlb(outpatientType.longValue());
            register.setYspb(ysbz);
            register.setSffs(0);
            register.setJzzt(0);
            register.setYybz(1);
            register.setGhlb(ghlb);
            register.setGhsj(sourceNumber.getQssj());
            register.setSfsj(now);
            register.setCzgh("900001");
            register.setKsdm(sourceNumber.getGhks());
            register.setJzhm(jzhm);
            register.setZblb(sourceNumber.getZblb());
            register.setYsdm(ysdm);
            register.setBrid(appointmentInfomation.getBrid());
            //病人性质写死1000
            register.setBrxz(1000L);
            register.setDzfpbz(dzfpbz);
            //医保暂时不使用
//            ybkh = appointmentMapper.getYbkh(appointmentInfomation.getSfzh());
//            logger.info("====医保卡号 --> {}", ybkh);
//            if(StringUtils.isNotBlank(ybkh)){
//                SignParam signParam = new SignParam();
//                signParam.setCardNum(ybkh);
//                signParam.setYgdm("1101");
//                signParam.setCzbm("100000");
//                signParam.setRegistrationDate(DateUtil.dateFormat1(new Date()));
//                signParam.setDepartmentName(sourceNumber.getGhks());
//                signParam.setDoctorCode(ysdm);
//                if(payAmount == null){
//                    payAmount = 0.00;
//                }
//                signParam.setInspectionFees(payAmount);
//                signParam.setMedicalCategory("11");
//                SignResponse signResponse = ybService.sign(signParam);
//                logger.info("登记参数======>{}",signResponse);
//                if(signResponse != null){
//                    fsfjylsh = signResponse.getYyjylsh();
//                    PersonalInfoDomain personalInfoDomain = ybService.getPersonalInfoDomain("1101", "100000", ybkh);
//                    logger.info("=========== personalInfoDomain : {} ===========",personalInfoDomain);
//                    register.setDjlsh(signResponse.getMzlsh());
//                    register.setZxjylsh(signResponse.getJyls());
//                    register.setFsfjylsh(signResponse.getYyjylsh());
//                    register.setYllb("11");
//                    register.setRylb(personalInfoDomain.getType());
//                    register.setTcqh(personalInfoDomain.getCoordinatingAreaCode());
//                    register.setBxtc(signResponse.getOverallPayment());
//                    register.setBxzh(0);
//                    register.setYwzqh(signResponse.getZqh());
//                    register.setYbzhye(Double.parseDouble(personalInfoDomain.getAccountBalance()));
//                    register.setApplx(5L);
//
//                    //ycjb_djjl
//                    YcRequest ycRequest = new YcRequest();
//                    ycRequest.setBRXM(appointmentInfomation.getBrxm());
//                    ycRequest.setBXTC(String.valueOf(signResponse.getOverallPayment()));
//                    ycRequest.setBXZH("0");
//                    ycRequest.setBY01("0");
//                    ycRequest.setBY02("0");
//                    ycRequest.setBY03("0");
//                    ycRequest.setDJLSH(signResponse.getMzlsh());
//                    ycRequest.setDJLX(1);
//                    ycRequest.setDJSJ(DateUtil.dateFormat1(new Date()));
//                    ycRequest.setFSFJYLSH(signResponse.getYyjylsh());
//                    ycRequest.setZXJYLSH(signResponse.getJyls());
//                    ycRequest.setYWZQH(signResponse.getZqh());
//                    ycRequest.setYSDM(ysdm);
//                    ycRequest.setYLLB("11");
//                    ycRequest.setYBKH(ybkh);
//                    ycRequest.setXJJE(String.valueOf(signResponse.getCashExpenditure()));
//                    ycRequest.setTCQH(personalInfoDomain.getCoordinatingAreaCode());
//                    ycRequest.setRYLB(personalInfoDomain.getType());
//                    ycRequest.setMZZYH(ghmx);
//                    ycRequest.setJBR("900001");
//                    ycRequest.setGHF("0");
//                    ycRequest.setJCF(String.valueOf(payAmount));
//                    ycRequest.setKSMC(sourceNumber.getKsmc());
//                    ycRequest.setQXBZ(0L);
//                    ycRequest.setJYRQ(new Date());
//                    ycRequest.setGRBH(personalInfoDomain.getNum());
//                    logger.info("====== ycRequest:{} =====", ycRequest);
//                    appointmentRegisterMapper.insertYcjb(ycRequest);
//                    logger.info("ycRequest insert success");
//                }
//            }
            logger.info("register --> {}", register);
            registerMapper.insertRegister(register);
            logger.info("register insert success");


            userBillManager.updateJzhm(jgid, "", jzhm);

            //MS_GH_FKXX
            PaymentInformationDomain paymentInformation = new PaymentInformationDomain();
            paymentInformation.setAppfkfs("1");
            paymentInformation.setJlxh(fkxh);
            paymentInformation.setFkfs(Long.parseLong(payMode));
            if (payAmount == null) {
                payAmount = 0.00;
            }
            paymentInformation.setFkje(payAmount);
            paymentInformation.setSbxh(ghmx);
            paymentInformation.setFkhm(agtOrderNumber);


            paymentInformationMapper.insertPaymentInformation(paymentInformation);


            //回写 GHYY_YYXX
            appointmentInfomation.setGhsj(now);
            appointmentInfomation.setYyzt((long) 1);
            appointmentInfomation.setFkbz(1);
            appointmentInfomation.setGhr("900001");
            appointmentInfomation.setGhxh(ghmx);
            appointmentInfomation.setGhr("900001");
            appointmentInfomation.setApplx(5L);

            appointmentInfomationMapper.updateAppointmentInfo(appointmentInfomation);

            //GHYY_HYXX
            sourceNumber.setGhxh(ghmx);
            sourceNumber.setCzgh("900001");
            sourceNumber.setCzrq(new Date());
            //sourceNumber.setBrid(brid);
            //sourceNumber.setBrxm(brxm);
            sourceNumberMapper.updateSourceNumber(sourceNumber);

            //createOrderNoMapper.updateShddhYwzt(outOrderNumber, 1, jgid.intValue());
            createOrderNoMapper.updateShddhZfzt(outOrderNumber, 1, new Date(), zffs, jgid.intValue(), agtOrderNumber, jzhm);
            //是否进队列 0不进 1 进入队列
            if (enterQueue != null && "1".equals(enterQueue.toString())) {
                BaseResponse<String> pdjhResponse = queueCallService.insertPdjh(
                        jgid.intValue(),
                        sourceNumber.getBrid().intValue(),
                        sourceNumber.getBrxm(),
                        sourceNumber.getGhks(),
                        sourceNumber.getKsmc(),
                        sourceNumber.getYsdm(),
                        sourceNumber.getYsxm(),
                        ghmx.intValue(),
                        yyxh.intValue(),
                        sourceNumber.getSxh(),
                        sourceNumber.getQssj(),
                        sourceNumber.getZblb(),
                        czpb.intValue());
                if (pdjhResponse.getCode() != Constant.successTag && pdjhResponse.getCode() != Constant.successResponse) {

                    baseResponse.setCode(pdjhResponse.getCode());
                    baseResponse.setMessage(pdjhResponse.getMessage());

                    return baseResponse;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            if(StringUtils.isNotBlank(fsfjylsh) && StringUtils.isNotBlank(ybkh)){
//                logger.info("出现异常，撤销登记！");
//                OutResponse outResponse = ybService.out(fsfjylsh, "900001", "1101", ybkh);
//                logger.info("======= 异常撤销结果:{} ==========",outResponse);
//            }
        }

        ret = notify;

//		ret = ghmx.toString();

        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(String.valueOf(ghmx));
        return baseResponse;
    }

    public List<DeptAndDoctorDomain> queryDeptAndDoctor(String hospitalCode, String query, Integer outpatientType) {

        List<DeptAndDoctorDomain> deptAndDoctorList = new ArrayList<>();

        Long jgid;

        jgid = Long.parseLong(hospitalCode);

        //先查科室
        List<ChildDepartment> childDepartmentList = departmentMapper.getChildDepartByName(jgid, query, outpatientType);

        if (childDepartmentList == null || childDepartmentList.size() <= 0) {
            //未找到再查医生
            List<Doctor> doctorList = doctorMapper.getDoctorByName(jgid, query);
            if (doctorList != null && doctorList.size() > 0) {
                for (Doctor doctor : doctorList) {
                    DeptAndDoctorDomain deptAndDoctor = new DeptAndDoctorDomain();
                    deptAndDoctor.setDoctorCode(doctor.getDoctorId());
                    deptAndDoctor.setDoctorName(doctor.getDoctorName());
                    deptAndDoctor.setDtype("2");
                    deptAndDoctorList.add(deptAndDoctor);
                }
            }

        } else {
            for (ChildDepartment department : childDepartmentList) {
                DeptAndDoctorDomain deptAndDoctor = new DeptAndDoctorDomain();
                deptAndDoctor.setDepartmentCode(department.getDepartmentId());
                deptAndDoctor.setDepartmentName(department.getDepartmentName());
                deptAndDoctor.setDtype("1");
                deptAndDoctorList.add(deptAndDoctor);
            }
        }

        return deptAndDoctorList;

    }

    /**
     * 由运营商系统调用，返回前一天的预约记录的执行情况。建议每天凌晨4点调用一次。
     *
     * @return
     */
    public BaseResponse<List<SyncOrderState>> syncOrderState(SyncOrderStatePoJo syncOrderStatePoJo) {

        BaseResponse<List<SyncOrderState>> response = new BaseResponse<>();
        List<SyncOrderState> list = new ArrayList<>();

        try {
            list = appointmentMapper.syncOrderState(syncOrderStatePoJo);
            response.setCode(Constant.successTag);
            if (list.size() > 0) {
                response.setMessage("处理成功");
                response.setData(list);
            } else {
                response.setMessage("未查询到数据！");
                response.setData(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(Constant.errorTag);
            response.setMessage("处理失败");
        }


        return response;
    }

    /**
     * 执行退号通知时调用。
     *
     * @return
     */
    public Map<String, Object> refundNotice(String hospitalCode, String hisOrderNumber) {

        Map<String, Object> map = null;

        return map;
    }

    /**
     * 预约挂号服务
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<BookingRegisterDomain> saveYYGH(BookingRegisterPojo pojo) throws Exception {
        logger.info("BookingRegisterPojo ---> {}", pojo);
        BaseResponse<BookingRegisterDomain> response = new BaseResponse<>();
        String brid = pojo.getPatientId();
        String jgid = "1";
        if (!"".equals(brid) && brid != null) {
            //校验brid
            Integer bridBrda = appointmentMapper.getBridBrda(Integer.valueOf(brid));
            if (bridBrda == null || bridBrda == 0) {
                response.setCode(Constant.errorTag);
                response.setMessage("参数病人ID无效,暂时不能预约");
                return response;
            }
            //1.判断病人是否可以预约
            Integer mdbz = appointmentMapper.getMdbz(brid, jgid);
            if (mdbz > 0) {
                //黑名单中有这个人,判断现在的时间是否大于这个人的退出时间，如果大于则可以进行预约1，如果小于不能预约0
                GHHMD isyy = appointmentMapper.getIsYY(brid, jgid);
                if (isyy.getKZBZ() == 0) {
                    //不能预约
                    response.setCode(Constant.errorTag);
                    response.setMessage("该病人已进入黑名单,暂时不能预约");
                    return response;
                } else {
                    //更新黑名单表中数据
                    appointmentMapper.updateBrzt(brid, jgid);
                }
            }
        } else {
            //没有BRID时判断病人信息是否为空
            if (pojo.getPatientSex() == -1) {
                response.setCode(Constant.errorTag);
                response.setMessage("性别不能为空");
                return response;
            }
            if (pojo.getCardType() != 1) {
                response.setCode(Constant.errorTag);
                response.setMessage("证件类型必须为身份证类型");
                return response;
            }
            if (pojo.getCardNumber() == null || "".equals(pojo.getCardNumber())) {
                response.setCode(Constant.errorTag);
                response.setMessage("身份证号码不能为空");
                return response;
            }

//			brid= String.valueOf(appointmentMapper.getBridSfzh(pojo.getCardNumber())) ;
//			if(brid==null||"".equals(brid)){
//				brid="0";
//			}

            PatientInfoDomain patientInfo = appointmentMapper.getBridSfzh(pojo.getCardNumber());
            if (patientInfo == null) {
                brid = "0";
            } else {
                brid = patientInfo.getBRID().toString();
            }

        }
        //进行预约
        //1.判断号源是否被使用
        HYXX hyxx = appointmentMapper.getHyxx(pojo.getResourceId(), pojo.getOrganizationId());
        if (hyxx != null) {
            if (hyxx.getYYXH() > 0) {
                response.setCode(Constant.errorTag);
                response.setMessage("此号源已被预约");
                return response;
            }
            if (hyxx.getGHXH() > 0) {
                response.setCode(Constant.errorTag);
                response.setMessage("此号源已被挂号");
                return response;
            }
        } else {
            response.setCode(Constant.errorTag);
            response.setMessage("无法获取该号源信息");
            return response;
        }
        //获取预约序号
        long yyxh = identityManager.getMax("GHYY_YYXX", 1);
        //进行预约保存
//		if (pojo.getPatientIdentityCardType()==1){
////			sfzh = pojo.getPatientIdentityCardNumber();
////		}
        BookingRegisterDomain bookingRegisterDomain = new BookingRegisterDomain();
        String yyjylsh = "";
        String ybkh = "";
        try {
            //预约保存
            appointmentMapper.insertGHYY(yyxh, jgid, brid,
                    pojo.getPatientName(), pojo.getPatientSex(), pojo.getCardNumber().trim(), pojo.getPatientMobile(), pojo.getResourceId(), 9, hyxx.getQSSJ());
            //更新号源信息
            logger.info("==== GHYY_HYXX : yyxh={}", yyxh);
            logger.info("==== GHYY_HYXX : pojo={}", pojo);
            appointmentMapper.updateHyxx(yyxh, brid, pojo.getPatientName(), pojo.getResourceId(), jgid);


            //获取返回前端的信息
            bookingRegisterDomain = appointmentMapper.getAddress(pojo.getDoctorId(), pojo.getDepartmentId(), jgid);
            bookingRegisterDomain.setXjzc(Double.parseDouble(pojo.getRegFee()));
//            ybkh = appointmentMapper.getYbkh(pojo.getCardNumber());
//            logger.info("预约挂号医保卡号: ===> {}",ybkh);
            //如果医保卡号不为空，则调用 医保门诊登记
//            if (StringUtils.isNotBlank(ybkh)) {
//                String ywzqh = ybService.getzqh();
//                logger.info("预约挂号时 周期号：====>{}",ywzqh);
//                SignParam signParam = new SignParam();
//                signParam.setCardNum(ybkh);
//                signParam.setYbzqh(ywzqh);
//                signParam.setYgdm(jgid);
//                signParam.setCzbm("900001");
//                signParam.setRegistrationDate(DateUtil.dateFormat1(new Date()));
//                signParam.setDepartmentName(pojo.getDepartmentId());
//                signParam.setDoctorCode(pojo.getDoctorId());
//                signParam.setInspectionFees(Double.parseDouble(pojo.getRegFee()));
//                signParam.setMedicalCategory("11");
//                SignResponse signResponse = ybService.sign(signParam);
//                logger.info("预约挂号时回参：====>{}",signResponse);
//                //登记成功，返回登记发送流水号，账户支出，现金支出
//                if (signResponse != null) {
//                    yyjylsh = signResponse.getYyjylsh();
//                    //预存门诊登记流水号
//                    Integer count = appointmentMapper.insertMzlsh(pojo.getCardNumber(), signResponse.getMzlsh());
//                    //封装登记发送流水号，账户支出，现金支出
//                    bookingRegisterDomain.setZhzc(signResponse.getAccountExpenditure());
//                    bookingRegisterDomain.setXjzc(signResponse.getCashExpenditure());
//                    bookingRegisterDomain.setTczf(signResponse.getOverallPayment());
//                    logger.info("撤销门诊流水号：====>{}",signResponse.getMzlsh());
//                    OutResponse outResponse = ybService.out(signResponse.getYyjylsh(), "900001", "1101", ybkh);
//                    logger.info("预约挂号撤销后回参：====>{}",outResponse);
//                    PersonalInfoDomain personalInfoDomain = ybService.getPersonalInfoDomain("1101", "100000", ybkh);
//                    logger.info("=========== personalInfoDomain : {} ===========",personalInfoDomain);
//
//                    //ycjb_djjl
//                    Date newDate = new Date();
//                    String date = DateUtil.dateFormat1(new Date());
//                    YcRequest ycRequest = new YcRequest();
//                    ycRequest.setBRXM(pojo.getPatientName());
//                    ycRequest.setBXTC(String.valueOf(signResponse.getOverallPayment()));
//                    ycRequest.setBXZH("0");
//                    ycRequest.setBY01("0");
//                    ycRequest.setBY02("0");
//                    ycRequest.setBY03("0");
//                    ycRequest.setDJLSH(signResponse.getMzlsh());
//                    ycRequest.setDJLX(1);
//                    ycRequest.setDJSJ(date);
//                    ycRequest.setFSFJYLSH(signResponse.getYyjylsh());
//                    ycRequest.setZXJYLSH(signResponse.getJyls());
//                    ycRequest.setYWZQH(signResponse.getZqh());
//                    ycRequest.setYSDM(pojo.getDoctorId());
//                    ycRequest.setYLLB("11");
//                    ycRequest.setYBKH(ybkh);
//                    ycRequest.setXJJE(String.valueOf(signResponse.getCashExpenditure()));
//                    ycRequest.setTCQH(personalInfoDomain.getCoordinatingAreaCode());
//                    ycRequest.setRYLB(personalInfoDomain.getType());
//                    ycRequest.setMZZYH(0L);
//                    ycRequest.setGHF("0");
//                    ycRequest.setJBR("900001");
//                    ycRequest.setJCF(String.valueOf(pojo.getRegFee()));
//                    ycRequest.setKSMC(pojo.getDepartmentId());
//                    ycRequest.setQXBZ(0L);
//                    ycRequest.setJYRQ(new Date());
//                    ycRequest.setGRBH(personalInfoDomain.getNum());
//                    ycRequest.setQXJYRQ(newDate);
//                    ycRequest.setQXYWZQH(signResponse.getZqh());
//                    logger.info("====== ycRequest:{} =====", ycRequest);
//                    appointmentRegisterMapper.insertYcjb(ycRequest);
//                    logger.info("ycRequest insert success");
//
//                }
//            }
            bookingRegisterDomain.setOrganizationId(pojo.getOrganizationId());
            bookingRegisterDomain.setOrderId(String.valueOf(yyxh));
            bookingRegisterDomain.setSource(String.valueOf(pojo.getSource()));
            bookingRegisterDomain.setResourceId(pojo.getResourceId());
            bookingRegisterDomain.setPatientId(brid);
            bookingRegisterDomain.setScheduleDate(DateUtil.dateFormat(hyxx.getQSSJ()));
        } catch (Exception e) {
            e.printStackTrace();
//            if(StringUtils.isNotBlank(yyjylsh) && StringUtils.isNotBlank(ybkh)){
//                logger.info("======== 异常撤销 ======");
//                OutResponse outResponse = ybService.out(yyjylsh, "900001", "1101", ybkh);
//                logger.info("======== 异常撤销:{} ======",outResponse);
//            }

        }


        response.setCode(Constant.successTag);
        response.setData(bookingRegisterDomain);
        return response;
    }

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> returnVisitPaymentAndSettlement(ReturnVisitPaymentAndSettlementPojo retVisit) {
        logger.info("=========== retVisit : {} =============", retVisit);
        BaseResponse<String> baseResponse = new BaseResponse<>();
        Long jgid;
        Long applx = 8L;
        if (retVisit.getOrganizationId() == null || "".equals(retVisit.getOrganizationId())) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("医院代码不能为空!");
            return baseResponse;
        }
        jgid = 1L;

        if (retVisit.getPatientId() == null || "".equals(retVisit.getPatientId())) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("病人代码不能为空!");
            return baseResponse;
        }

        Long brid = Long.parseLong(retVisit.getPatientId());

        //根据病人id获取病人档案
        PatientDomain patient = patientMapper.getPatientById(brid);
        if (patient == null) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("未找到该病人id的档案!");
            return baseResponse;
        }

        String jzhm;
        jzhm = userBillManager.getJzhm(jgid, "");

        if (jzhm == null || "".equals(jzhm)) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("获取掌上医院默认员工就诊号码票据失败!");
            return baseResponse;
        }

        if (StringUtils.isBlank(retVisit.getAppointmentTime())) {
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("挂号时间不能为空!");
            return baseResponse;
        }

        if(StringUtils.isBlank(retVisit.getConsultType())){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("问诊类型不能为空!");
            return baseResponse;
        }

        if(StringUtils.isBlank(retVisit.getQuestion())){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("患者病情不能为空!");
            return baseResponse;
        }

        if(retVisit.getConsultId() == null){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("咨询组件不能为空!");
            return baseResponse;
        }

        if(retVisit.getAppointmentTime() == null){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("预约时间不能为空!");
            return baseResponse;
        }

        if(StringUtils.isBlank(retVisit.getTimeFlag())){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("值班类别不能为空!");
            return baseResponse;
        }

        Date ghsj = DateUtil.StrToFormatDate(retVisit.getAppointmentTime(), "yyyy-MM-dd HH:mm:ss");

        //插入MS_GHMX
        Long ghmx = identityManager.getMax("MS_GHMX", 1);
        Long fkxh = identityManager.getMax("MS_GH_FKXX", 1);

        Date now = new Date();
        Double regFee = retVisit.getRegFee();
        if (regFee == null) {
            regFee = 0.00;
        }
        Integer ysbz = 1;
        if (retVisit.getDoctorId() == null || "".equals(retVisit.getDoctorId())) {
            ysbz = 0;
        }
        List<HyxxDomain> sxh = appointmentMapper.getSXh(1, retVisit.getDepartmentId(), DateUtil.StrToFormatDate(retVisit.getAppointmentTime(),"yyyy-MM-dd HH:mm:ss"), retVisit.getDoctorId(),Integer.valueOf(retVisit.getTimeFlag()));
        if(sxh == null || sxh.size() == 0){
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("查询不到预约序号！");
            return baseResponse;
        }

        //更新号源信息
        try {
            appointmentMapper.updateHyxx(ghmx,patient.getBrid().toString(),patient.getBrxm(),sxh.get(0).getJLXH().toString(),"1");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            baseResponse.setCode(Constant.breakTag);
            baseResponse.setMessage("预约信息更新失败！");
            return baseResponse;
        }

        Integer ghlb = appointmentMapper.getGhlb(retVisit.getDepartmentId());
        //MS_GHMX
        RegisterDomain register = new RegisterDomain();
        register.setSbxh(ghmx);
        register.setJgid(jgid);
        register.setJzxh(sxh.get(0).getSXH());
        register.setGhcs(1);
        register.setGhje(0.00);
        register.setZlje(regFee);
        register.setZjfy(0.00);
        register.setBlje(0.00);
        register.setJzje(0.00);
        register.setQtys(0.00);
        register.setThbz(0);
        register.setCzpb(1);
        register.setMzlb(retVisit.getOutpatientType().longValue());
        register.setYspb(ysbz);
        register.setSffs(0);
        register.setJzzt(0);
        register.setYybz(0);
        register.setGhlb(ghlb);
        register.setGhsj(sxh.get(0).getQSSJ());
        register.setSfsj(now);
        register.setKsdm(retVisit.getDepartmentId());
        register.setJzhm(jzhm);
        register.setZblb(0);
        register.setYsdm(retVisit.getDoctorId());
        register.setBrid(brid);
        register.setBrxz(patient.getBrxz());
        //todo 需要申请新的工号
        register.setCzgh("900002");
        register.setApplx(applx);
        register.setAppzfdjh(retVisit.getAgtOrderNumber());
        register.setAppzffs("1");
        register.setAppzfje(regFee);

        registerMapper.insertRegister(register);
        logger.info("======== register insert success ======");

        userBillManager.updateJzhm(jgid, "", jzhm);

        //预约信息保存
        //获取预约序号
        long yyxh = identityManager.getMax("GHYY_YYXX", 1);
        appointmentMapper.insertYYXX(yyxh, "1", brid.toString(),
                patient.getBrxm(), patient.getBrxb(), patient.getSfzh(), patient.getLxdh(), sxh.get(0).getJLXH().toString(), 5, sxh.get(0).getQSSJ(),8,ghmx,retVisit.getConsultType(),retVisit.getConsultId().toString(),retVisit.getQuestion());

        logger.info("======== YYXX insert success ======");

        //MS_GH_FKXX
        Double payAmount = null;
        PaymentInformationDomain paymentInformation = new PaymentInformationDomain();
        paymentInformation.setAppfkfs("1");
        paymentInformation.setJlxh(fkxh);
        //默认付款方式
        paymentInformation.setFkfs(1L);
        if (retVisit.getRegFee() == null) {
            payAmount = 0.00;
        } else {
            payAmount = retVisit.getRegFee();
        }
        paymentInformation.setFkje(payAmount);
        paymentInformation.setSbxh(ghmx);
        if (StringUtils.isNotBlank(retVisit.getAgtOrderNumber())) {
            paymentInformation.setFkhm(retVisit.getAgtOrderNumber());
        }
        paymentInformationMapper.insertPaymentInformation(paymentInformation);
        logger.info("======== paymentInformation insert success ======");

        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(ghmx.toString());

        return baseResponse;
    }

    public Integer updateInfo(String ybkh, String sfzh, Integer brxz) {
        int i = appointmentRegisterMapper.updateBrda(ybkh, sfzh, brxz);
        return i;
    }

    public BaseResponse<String> selectMedicalCardNum(String sfzh) {
        logger.info("入参 身份证号码:=====>{}", sfzh);
        BaseResponse<String> baseResponse = new BaseResponse<>();
        String medicalCardNum = appointmentRegisterMapper.searchMedicalCardNum(sfzh);
        if (StringUtils.isNotBlank(medicalCardNum)) {
            baseResponse.setData(medicalCardNum);
            baseResponse.setCode(200);
            baseResponse.setMessage("查询成功！");
        } else {
            baseResponse.setCode(-1);
            baseResponse.setMessage("查询失败！");
        }
        return baseResponse;
    }
}
